import jwt from "jsonwebtoken";
import { key } from "../config/config.default.js";
import { errorResponse } from "../utils/result.js";

export const signToken = (user) => {
  const token = jwt.sign(
    { id: user._id, phone: user.phone, password: user.password },
    key,
    {
      expiresIn: "1d",
    }
  );
  return token;
};

/**
 * jwt校验
 */
export const verifyToken = function (requried = true) {
  return (req, res, next) => {
    var token = req.headers.authorization;
    token = token ? token.split("Bearer ")[1] : null;
    if (token) {
      try {
        let user = jwt.verify(token, key);
        delete user.password;
        req.user = user;
        next();
      } catch (err) {
        res.status(401).json(errorResponse("token验证失败"));
      }
    } else if (requried) {
      res.status(401).json(errorResponse("当前未登录，请先登录"));
    } else {
      next();
    }
  };
};
